<?php
namespace Buu\Modules\HaohaoceManager\Lib;

class Podinfo
{
	const DIR_YAML_RUNNING = '/qa-ali-nfs/buu_haohaoce/hhc_k8s_yaml_running';
	const STATUS_UNREADY = 0;
	const STATUS_READY = 1;

	static public function is_pod_id($pod_id){
		return preg_match('/[0-9]+\-[0-9]+/', $pod_id);
	}
	static public function add($pod_id , $info){
		$running_desc_json_path = self::DIR_YAML_RUNNING.'/'.$pod_id.'-desc.json';
		file_put_contents($running_desc_json_path , json_encode($info));
	}
	static public function list_all(){
		$podinfos = array();
		$path = self::DIR_YAML_RUNNING.'/*-desc.json';
		$list = glob($path);
		if(!empty($list)){
			foreach ($list as $path) {
				$tmp = json_decode(file_get_contents($path) , 1);
				$podinfos[$tmp['pod_id']] = $tmp;
			}
		}
		return $podinfos;
	}
	static public function get_by_podid($pod_id){
		$running_desc_json_path = self::DIR_YAML_RUNNING.'/'.$pod_id.'-desc.json';
		return json_decode(file_get_contents($running_desc_json_path) , 1);
	}
	static public function set_by_podid($pod_id , $info){
		$info_ori = self::get_by_podid($pod_id);
		$info = array_merge($info_ori , $info);
		$running_desc_json_path = self::DIR_YAML_RUNNING.'/'.$pod_id.'-desc.json';
		file_put_contents($running_desc_json_path , json_encode($info));	
	}
	static public function set_ready_by_podid($pod_id){
		self::set_by_podid($pod_id , ['status' => self::STATUS_READY]);
	}
	static public function set_alerted_by_podid($pod_id){
		self::set_by_podid($pod_id , ['alerted' => 1]);
	}
	static public function del_by_podid($pod_id){
		$running_desc_json_path = self::DIR_YAML_RUNNING.'/'.$pod_id.'-desc.json';
		unlink($running_desc_json_path);
	}
	static public function delay_expire_by_podid($pod_id , $hour = 2){
		$info_ori = self::get_by_podid($pod_id);
		$expire_timestamp = strtotime($info_ori['expire']);
		$expire_timestamp += $hour*60*60;
		self::set_by_podid($pod_id , ['expire' => date('Y-m-d H:i:s' , $expire_timestamp)]);
	}


	static public function formatPodInfo($pod_id , $admin_id ,$admin_name,$admin_email , $pod_type , $pod_resource,$domain_suffix, $expire , $desc , $env = null , $status = 0){
		return array(
			'pod_id' => $pod_id,
			'admin_id' => $admin_id,
			'admin_name' => $admin_name,
			'admin_email' => $admin_email,
			'pod_type' => $pod_type,
			'pod_resource' => $pod_resource,
			'domain_suffix' => $domain_suffix,
			'expire' => $expire,
			'desc' => $desc,
			'env' => $env,
			'status' => $status,
			'pod_name' => '',
			'svc_name' => '',
			'create_time' => '',
		);
	}
}